package 力扣日常刷题.木23一月.第07天307;

import java.util.Arrays;

/**
 * @author 帅小伙
 * @date 2022/3/7
 * @description
 */
public class Demo04向数组中追加K个整数 {

    public long minimalKSum(int[] nums, int k) {
        Arrays.sort(nums);
        long sum = (k + 1l) * k / 2;
        long count = k;
        if (nums[0] > k) return sum;
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            // 当前这个位置被占了
            // count - sum 个元素需要多+1  count的位置也向后移
            if (nums[i] <= count) {
                count += 1;
                sum = sum - nums[i] + count;
            } else break;
        }
        return sum;
    }


    public long cal(int[]nums,int k) {
        Arrays.sort(nums);
        long sum = (1l+k) * k / 2;
        int count = k;
        for (int i = 0; i < nums.length; i++) {
            if(i >0 && nums[i] == nums[i - 1])continue;
            if(nums[i] <= count) {
                count += 1;
                sum = sum + count - nums[i];
            }
        }
        return sum;
    }

}
